﻿using Coldairarrow.Business.MEGA;
using Coldairarrow.Entity.Base_Manage;
using Coldairarrow.Entity.MEGA;
using Coldairarrow.Util;
using EFCore.Sharding;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using SelectPdf;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Coldairarrow.Api.Controllers
{
    [Route("/[controller]/[action]")]
    public class TestController : BaseController
    {
        readonly IDbAccessor _repository;
        readonly IHostingEnvironment _hostingEnv;
         
        public TestController(IDbAccessor repository, IHostingEnvironment hostingEnv)
        {
            _repository = repository;
            _hostingEnv = hostingEnv;
        }

        [HttpGet]
        public async Task PressTest()
        {
            Base_User base_User = new Base_User
            {
                Id = Guid.NewGuid().ToString(),
                Birthday = DateTime.Now,
                CreateTime = DateTime.Now,
                CreatorId = Guid.NewGuid().ToString(),
                DepartmentId = Guid.NewGuid().ToString(),
                Password = Guid.NewGuid().ToString(),
                RealName = Guid.NewGuid().ToString(),
                Sex = Sex.Man,
                UserName = Guid.NewGuid().ToString()
            };

            await _repository.InsertAsync(base_User);
            await _repository.UpdateAsync(base_User);
            await _repository.GetIQueryable<Base_User>().Where(x => x.Id == base_User.Id).FirstOrDefaultAsync();
            await _repository.DeleteAsync(base_User);
        }

        [HttpGet]
        public async Task<PageResult<Base_UserLog>> GetLogList()
        {
            return await _repository.GetIQueryable<Base_UserLog>().GetPageResultAsync(new PageInput());
        }
        public class PdfDTO
        {
            public string id { get; set; }
            public int Type { get; set; }
        }


      
        /// <summary>
        /// 转pdf
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        [NoCheckJWT]
        public string GetPdf(PdfDTO input)
        {
            string id = input.id; //叶片id
            string tPath = "";
            List<object> dList = new List<object>();

            SelectPdf.PdfDocument docHtml = null;

            var Data = string.Empty;
            string Name = "";

            var GetList = CreateQrCode(id);
            Data = YPPDF(GetList);
            Name = "叶片二维码信息查看.pdf";

            HtmlToPdf Renderer = new HtmlToPdf();
            //设置Pdf参数
            Renderer.Options.PdfPageOrientation = PdfPageOrientation.Landscape;//设置页面方式-横向  PdfPageOrientation.Portrait  竖向
            Renderer.Options.PdfPageSize = PdfPageSize.A4;//设置页面大小，30种页面大小可以选择
            Renderer.Options.MarginTop = 10;   //上下左右边距设置  
            Renderer.Options.MarginBottom = 10;
            Renderer.Options.MarginLeft = 10;
            Renderer.Options.MarginRight = 10;
            //设置更多额参数可以去HtmlToPdfOptions里面选择设置

            if (docHtml == null)
                docHtml = Renderer.ConvertHtmlString(Data);//根据html内容导出PDF 
            else
                //在上一个pdf元素页面下面追加Pdf页面，官方文档对于一个pdf文件打印多页的处理提供了分页符，在你想打印一页的元素外面加上   <div style="font-size: 28px; page-break-after: always">元素
                //也就是分页符，但是试用感觉效果并不理想，下面这个Append追加一个pdf页面效果会更好点，但是可能会损耗一些性能
                docHtml.Append(Renderer.ConvertHtmlString(Data));


            string webRootPath = _hostingEnv.ContentRootPath;  //获取项目运行绝对路径
            var path = $"/wwwroot/ExportPDF/{DateTime.Now.ToString("yyyyMMdd")}/";//文件相对路径
            var savepathHtml = $"{webRootPath}{path}{Guid.NewGuid().ToString()}-Html.pdf";//保存绝对路径
            if (!Directory.Exists(Path.GetDirectoryName(webRootPath + path)))
            {
                Directory.CreateDirectory(Path.GetDirectoryName(webRootPath + path));
            }
            docHtml.Save(savepathHtml);
            // vs.Pageone = savepathHtml.Replace($"{webRootPath}/wwwroot", " ");

            using (var sw = new FileStream(savepathHtml, FileMode.Open))
            {
                StreamReader mysr = new StreamReader(sw);
                var obj = new object();
                if (!savepathHtml.IsNullOrEmpty())
                {
                    tPath = "/ExportPDF" + savepathHtml.Split("ExportPDF")[1];
                    obj = new
                    {
                        FileName = Name,
                        FilePath = tPath,
                        UploadTime = DateTime.Now
                    };
                    dList.Add(obj);

                    return tPath;
                }
            }
            return tPath;
        }

        /// <summary>
        /// 获取叶片二维码数据
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        private List<MEGA_QrCodeDTO> CreateQrCode(string id)
        {
            List<MEGA_QrCodeDTO> DataList = new List<MEGA_QrCodeDTO>();
            MEGA_QrCodeDTO datamodel = new MEGA_QrCodeDTO();

            #region---叶片信息--
            var q = _repository.GetIQueryable<MEGA_LeafBlade>().Where(x => x.Id.Equals(id));
            var qq = (from a in q
                      join b in _repository.GetIQueryable<MEGA_FactoryManagement>() on a.FactoryId equals b.Id
                      join c in _repository.GetIQueryable<MEGA_Material>() on a.MaterialId equals c.Id
                      select new MEGA_LeafBlade
                      {
                          Id = a.Id,
                          AreaId = a.AreaId,
                          AreaName = a.AreaName,
                          Code = a.Code,
                          CreateTime = a.CreateTime,
                          CreatorId = a.CreatorId,
                          Deleted = a.Deleted,
                          Describe = a.Describe,
                          Editor = a.Editor,
                          EditTime = a.EditTime,
                          FactoryId = a.FactoryId,
                          FactoryName = b.Name,
                          Image = a.Image,
                          Length = a.Length,
                          MaterialId = a.MaterialId,
                          MaterialName = c.Name,
                          Name = a.Name,
                          Note = a.Note,
                          PeopleId = a.PeopleId,
                          PeopleName = a.PeopleName,
                          Spec = a.Spec,
                          State = a.State
                      }).FirstOrDefault();
            #endregion

            if (qq != null)
            {
                datamodel.Leafmodel = qq;
                //工厂信息
                var gcqq = _repository.GetIQueryable<MEGA_FactoryManagement>().Where(e => e.Id.Equals(qq.FactoryId)).FirstOrDefault();
                if (gcqq != null)
                {
                    datamodel.Factorymodel = gcqq;
                }
            }

            DataList.Add(datamodel);
            return DataList;

        }

        private string YPPDF(List<MEGA_QrCodeDTO> data)
        {
            StringBuilder builder = new StringBuilder();
            #region Table style
            #endregion
            #region 2 Table
            string Header = $"<!DOCTYPE html>" +
                $" <html lang='en'>" +
                $" <head> " +
                $" <meta charset='UTF-8'> " +
                $" <meta name='viewport' content='width=device-width, initial-scale=1.0'>" +
                $"   <title>Document</title>" +
                $" </head>" +
                $" <style>   " +
       "*{margin:0;padding:0}body,html{width:100%;height:100%;}.bigBox{margin:0 auto; width:600px;height:600px;padding:20px;color:#04a548;font-size:20px;position:relative}.bigBox p{margin:8px}.bigBox .title1{text-align:center;margin:8px;font-size:40px}.bigBox .title2{text-align:center;margin:8px;font-size:28px;color:red}.top{border-bottom:4px solid #333;margin-bottom:40px}.down .goods{margin:8px;display:flex;justify-content:space-between}.down .goods p{width:48%;margin:0}.down .tip{color:red;font-size:16px}.erweima{position:absolute;right:20px;bottom:20px;width:170px;height:170px;}.down .inputRadio{display:flex;align-items:center;margin:8px}" +
$" </style> ";
            string htmlMode =
   $"             <body >" +
$"<div class='bigBox'>" +

$"			<div class='down'>" +
$"				<p>叶片信息</p>" +
$"				<div>" +
$"					<p>叶片名称：" + data[0].Leafmodel.Name + "</p>" +
$"					<p>编号：" + data[0].Leafmodel.Code + "</p>" +
$"					<p>规格：" + data[0].Leafmodel.Spec + "</p>" +
$"					<p>批次：" + data[0].Leafmodel.Batch + "</p>" +
$"					<p>长度：" + data[0].Leafmodel.Length + "</p>" +
$"					<p>加工时间：" + data[0].Leafmodel.CreateTime + "</p>" +
$"				</div>" +
$"				<p>-------------------------------------------------</p>" +
$"				<div>" +

$"				<p>工厂信息</p>" +
$"				<p>名称：" + data[0].Factorymodel.Name + "</p>" +
$"				<p>编号：" + data[0].Factorymodel.Code + "</p>" +
$"				<p>简介：" + data[0].Factorymodel.Describe + "</p>" +
$"				<p>地址：" + data[0].Factorymodel.Address + "</p>" +
$"				</div>" +
$"			</div>" +
$"		</div>" +
$"</body>" +
$"</html>";
            string P = Header + htmlMode;

            #endregion

            // builder.Append(htmlMode);
            //    builder.Append(styHtml);

            return P;
        }
    }
}